/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.task;

import akka.actor.ActorRef;
import com.cxhd.lis.DataCache;
import com.cxhd.lis.ctrl.actor.ActorManager;
import com.cxhd.lis.jsonbean.ResultBean;
import com.cxhd.lis.util.HttpClientUt;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
 *
 * @author 52461
 */
public class GetResultTask extends BaseTask {
    
    private Timer timer = new Timer();
    
    @Override
    public void start() {
        
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    doSvervice();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1000, 1000 * 10);
        
    }
    
    private void doSvervice() {
        if (checkGetDataFlag()) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("hospital_code", DataCache.getIntance().getLocalhostSN()));
            String returnData = HttpClientUt.httpPost("http://" + DataCache.getIntance().getConfig().get("lisCenterUrl") + "/lisPage/otherInfo/recviceData", params);
            if (returnData != null && returnData.length() > 0) {
                List<ResultBean> list = new Gson().fromJson(returnData, new TypeToken<List<ResultBean>>() {
                }.getType());
                parseResult(list);
            }
        }
        
    }
    
    public boolean checkGetDataFlag() {
        if (DataCache.getIntance().getConfig().get("autoGetDataForCenter") != null && DataCache.getIntance().getConfig().get("autoGetDataForCenter").equalsIgnoreCase("true")) {
            return Db.find("select * from lis_samplecollection where RETURN_RESULT_FLAG=0 and SEND_CENTER_STATUS=1 ").size() > 0;
        } else {
            
            return false;
        }
        
    }
    
    public void parseResult(List<ResultBean> list) {
        List<String> brcodeList = new ArrayList<String>();
        if (list != null && !list.isEmpty()) {
            
            for (ResultBean rb : list) {
                brcodeList.add(rb.getBARCODE());
                saveReuslt(rb);
            }
            updateCenterStatus(brcodeList);
            
        }
    }
    
    public void saveReuslt(ResultBean rb) {
        String uuid = null;
        String sample_no = null;
        List<Map<String, String>> rlist = rb.getResult();
        for (Map<String, String> re : rlist) {
            
            if (uuid == null) {
                uuid = re.get("uuid");
                sample_no = re.get("Sample_No");
            }
            Record r = new Record();
            r.set("Sample_No", re.get("Sample_No") + "")
                    .set("Item_pk", re.get("Item_pk"))
                    .set("Item_Code", re.get("Item_Code") + "")
                    .set("Item_Name", re.get("Item_Name") + "")
                    .set("Test_Value", re.get("Test_Value") + "")
                    .set("Flag_YQ", re.get("Flag_YQ") + "")
                    .set("High", re.get("High"))
                    .set("Low", re.get("Low"))
                    .set("Text_Danwei", re.get("Text_Danwei"))
                    .set("Text_Note", re.get("Text_Note"))
                    .set("Date_Test", re.get("Date_Test") + "")
                    .set("uuid", re.get("uuid") + "");
            Db.save("lis_result", r);
            
        }
        updatePatientInfo(rb);
        Db.update("update lis_samplecollection set EXAMINAIM='" + rb.getEXAMINAIM() + "', SAMPLENO='" + rb.getSAMPLENO() + "',UUID='" + rb.getUUID() + "', CHECKTIME='" + rb.getCHECKTIME() + "',JYYS='" + rb.getJYYS() + "',CHECKOPERATOR='" + rb.getCHECKOPERATOR() + "',SEND_CENTER_STATUS=2,RETURN_RESULT_FLAG=2 where BARCODE='" + rb.getBARCODE() + "' ");
        
    }
    
    public void sendMedicalCenter(){
    // Record re = Db.findFirst("select * from lis_samplecollection where BARCODE='" + rb.getBARCODE() + "' or  BARCODE='" + rb.getBARCODE() + "'");
        
     
    }
    
    public void updatePatientInfo(ResultBean rb) {
        Record rs = Db.findFirst("select * from lis_samplecollection where BARCODE='" + rb.getBARCODE() + "' or  BARCODE='" + rb.getBARCODE() + "'");
        
        
        
        try {
            if (rs != null) {
                Db.update("update lis_patient set PATIENTNAME='" + rb.getPATIENTNAME() + "',AGE='" + rb.getAGE() + "',SEX='" + rb.getSEX() + "' WHERE PK = '" + rs.get("INFOPK") + "'");
                 ActorManager.getIntance().getActor("SendDataActor").tell(rs.get("PK")+"", ActorRef.noSender());
            }            
        } catch (Exception ex) {
            
        }
        
       
    }
    
    public void updateCenterStatus(List<String> brcodeList) {
        String brcodes = StringUtils.join(brcodeList.toArray(), ",");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("hospital_code", DataCache.getIntance().getLocalhostSN()));
        params.add(new BasicNameValuePair("brcodes", brcodes));
        System.out.println(brcodes + "  更新服务器status");
        String returnData = HttpClientUt.httpPost("http://" + DataCache.getIntance().getConfig().get("lisCenterUrl") + "/lisPage/otherInfo/updateDataStatus", params);
        
    }
    
    @Override
    public void stop() {
        if (timer != null) {
            timer.cancel();
        }        
    }
    
}
